package app.sevenc.lib_framework.mvvm.v

import android.graphics.Color
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import app.sevenc.lib_framework.BaseFrameApplication
import app.sevenc.lib_framework.R
import app.sevenc.lib_framework.permission.PermissionProxy
import com.android.tools.r8.internal.it
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.KeyboardUtils

/**
 * Activity基类
 *
 * @author Seven-C
 * @date 2021/8/18
 */
abstract class BaseFrameActivity : AppCompatActivity(), IBaseFrameActivity {

    protected val mActivityProvider: ViewModelProvider by lazy { ViewModelProvider(this) }


    override fun onCreate(savedInstanceState: Bundle?) {
        onCreateBefore()
        super.onCreate(savedInstanceState)
    }

    override fun onCreateBefore() {
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        BarUtils.setStatusBarLightMode(this, true)
    }

    /**
     * 权限请求
     *
     * @param permissions Array<out String>
     * @param action Function1<Boolean, Unit>
     */
    fun requestPermission(vararg permissions: String, action: (Boolean) -> Unit) {
        PermissionProxy.requestPermission(this, listOf(*permissions)) {
            action(it)
        }
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘
     *
     * @param ev MotionEvent
     * @return Boolean
     */
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (isShouldHideKeyboard(v, ev)) {
                //关闭软键盘
                KeyboardUtils.hideSoftInput(this)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 如果焦点不是EditText则忽略
     *
     * @param v View?
     * @param event MotionEvent
     * @return Boolean
     */
    private fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.height
            val right = left + v.width
            return !(event.x > left && event.x < right
                    && event.y > top && event.y < bottom)
        }
        return false
    }
}